import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View} from '@tarojs/components';
import {TARO_ENV} from "../../../../constants/api";
import {lxH5Wx} from "../../../../utils/lx.h5.service";

export default class MapContainer extends Component {
  state: {
    map: any
    center: any
    bounds: any
    marker: any
    markerArr: any
    infoWindow: any
    tileImgLayer: any
    animation: boolean
    locationData: any
    markers: any
    polygons: any
  } = {
    map: null,
    center: null,
    bounds: null,
    marker: null,
    markerArr: [],
    infoWindow: null,
    tileImgLayer: [],
    animation: false,
    locationData: {},
    markers: [],
    polygons: []
  }

  async UNSAFE_componentWillMount() {
    if(TARO_ENV === 'h5') {
      //
    }else {
      //
    }
  }
  async componentDidMount() {
    const {boundary, scenicList} = this.props;
    // locationData
    if (TARO_ENV === 'h5') {
      this.initMap(boundary, scenicList)
    } else {
      this.initMapWeapp(boundary, scenicList)
    }
  }
  eventClick(evt) {
    lxH5Wx.navigation(evt.geometry.position.lat, evt.geometry.position.lng)
  }
  componentWillUnmount() {
    this.state.map && this.state.map.destroy();
  }
  // 计算地图中心
  calcMapCenterByBoundary(boundary) {
    const path = [
      boundary.getSouthWest(),
      boundary.getSouthEast(),
      boundary.getNorthEast(),
      boundary.getNorthWest()
    ];
    const position = new TMap.geometry.computeCentroid(path);
    return position;
  }
  initMapWeapp(boundary, scenicList) {
    let {locationData, markers} = this.state
    // 地图中心点
    const x1 = Number(boundary.longitude_left)
    const y1 = Number(boundary.latitude_left)
    const x2 = Number(boundary.longitude_right)
    const y2 = Number(boundary.latitude_right)
    /*locationData.latitude = ((y1-y2)/2 + y2).toFixed(6)
    locationData.longitude = ((x2-x1)/2 + x1).toFixed(6)*/
    locationData.latitude = ((y1-y2)/3 *2 + y2).toFixed(6)
    locationData.longitude = (x1).toFixed(6)
    markers = []
    // 地图标点
    scenicList.map((item, index) => {
      const markerObj = {
        uuid: item.scenic.uuid,
        id: index,
        latitude: item.scenic.latitude,
        longitude: item.scenic.longitude,
        iconPath: 'https://resource.ivcheng.com/upload/2022/08/31/0661a6f831fa4791ba40c6fb0ac2b402.png',
        width: 35,
        height: 35,
        label: {
          content: item.scenic.name.substr(0, 15),
          fontSize: 14,
          bgColor: '#f4f4f4',
          padding: 1,
          textAlign: 'right',
          anchorX: -(12 * item.scenic.name.substr(0, 15).length ) / 2,
        },
        zIndex: 9999
      };
      markers.push(markerObj)
    })

    /*const polygons = [{
      points:[
        {longitude: x1, latitude: y1},
        {longitude: x2, latitude: y1},
        {longitude: x2, latitude: y2},
        {longitude: x1, latitude: y2},
        {longitude: x1, latitude: y1},
      ],
      fillColor: "#DFEAFF99",
      strokeColor: "#548afc",
      strokeWidth: 2,
      zIndex: 1
    }]*/

    this.setState({locationData, markers})
  }
  initMap(boundary, scenicList) {
    // 计算地图中心
    const sw = new TMap.LatLng(boundary.latitude_right, boundary.longitude_left)
    const ne = new TMap.LatLng(boundary.latitude_left, boundary.longitude_right)
    const bounds = new TMap.LatLngBounds(sw, ne)
    const boundsCenter = this.calcMapCenterByBoundary(bounds);
    const center = new TMap.LatLng(boundsCenter.lat, boundsCenter.lng);
    //初始化地图
    const map = new TMap.Map("mapContainer", {
      zoom: 13,//设置地图缩放级别
      rotation: 353,
      center: center,//设置地图中心点坐标
      showControl: false
    });
    // 画选中的范围
    /*const boundaryCover = new TMap.LatLngBounds(sw, ne);
    const polygon = new TMap.MultiPolygon({
      map,
      geometries: [{
        paths: [
          boundaryCover.getSouthWest(),
          boundaryCover.getSouthEast(),
          boundaryCover.getNorthEast(),
          boundaryCover.getNorthWest()
        ]
      }]
    });*/
    // 点标记 - 中心
    let tempMarkers = []
    scenicList.map((item, index) => {
      const markerObj = {
        id: 'markerScenic',
        styleId: 'markerScenic', // 不同标注对应不同styleId
        position: new TMap.LatLng(Number(item.scenic.latitude), Number(item.scenic.longitude)),
        properties: {
          ...item,
          idx: index + 1
        },
        content: item.scenic.name.substr(0, 15)
      };
      tempMarkers.push(markerObj);
    })
    const marker = new TMap.MultiMarker({
      id: 'marker-layer',
      map: map,
      styles: {
        markerScenic: new TMap.MarkerStyle({
          width: 25,
          height: 25,
          anchor: { x: 13, y: 32 },
          src: 'https://resource.ivcheng.com/upload/2022/08/31/0661a6f831fa4791ba40c6fb0ac2b402.png',
          color: '#333', // 标注点文本颜色
          size: 14, // 标注点文本文字大小
          direction: 'bottom', // 标注点文本文字相对于标注点图片的方位
          offset: { x: 0, y: 8 }, // 标注点文本文字基于direction方位的偏移属性
          strokeColor: '#fff', // 标注点文本描边颜色
          strokeWidth: 2, // 标注点文本描边宽度
        })
      },
      geometries: tempMarkers,
    });
    marker.on("click", this.eventClick)
  }

  onChangeRegion = (event) => {
    if (typeof(event.detail.markerId) != "undefined" && event.detail.markerId != null) {
      const markers = this.state.markers
      for (let i=0; i<markers.length; i++) {
        if (markers[i].id == event.detail.markerId) {
          Taro.navigateTo({
            url: `/common/scenic/detail?itemId=${markers[i].uuid}`
          });
        }
      }
    } else {
      if (event.type === 'end' && event.causedBy === 'drag') { // 真机没有问题
        this.setState({
          animation: true
        })
      }
    }
  }

  render() {
    const {locationData, markers} = this.state;
    return (
      <View style='height: 95vh'>
        {TARO_ENV === 'h5' && <View id='mapContainer' className='map-container' style='height: 100% !important'></View>}
        {TARO_ENV === 'weapp' &&
        <map id='container' longitude={locationData.longitude} latitude={locationData.latitude} scale={9}
             markers={markers} onRegionChange={this.onChangeRegion} bindregionchange={this.onChangeRegion}
             bindmarkertap={this.onChangeRegion} style='width: 100%;height: 100vh;'
        ></map>}
      </View>
    )
  }
}
